package com.rtz.util;

import com.google.gson.Gson;
import org.apache.log4j.Logger;

import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

public class ResponseUtil {

	
	
	public static void wirte(HttpServletResponse response, Object object)
			throws Exception {
		response.setContentType("application/json;charset=utf-8");
		Logger logger = Logger.getLogger(ResponseUtil.class);
		logger.info(object);
		PrintWriter out = response.getWriter();
		out.println(object.toString());
		out.flush();
		out.close();

	}

	public static void handError(Map<String, Object> head,
			Map<String, Object> body, HttpServletResponse response,
			ResultCode code) throws Exception {

		Map<String, Object> returnMsg = new HashMap<>();
		body.put("ret_code", code.getCode());
		body.put("ret_msg", code.getMsg());

		returnMsg.put("head", head);
		returnMsg.put("body", body);

		ResponseUtil.wirte(response, new Gson().toJson(returnMsg));
	}

	/**
	 * 处理同步响应结果
	 * 
	 * @param head
	 * @param response
	 * @param code
	 * @throws Exception
	 */
	public static void handleSynchronousResponse(String result_order,
			String result_data, HttpServletResponse response, ResultCode code)
			throws Exception {

		Map<String, Object> returnMsg = new HashMap<>();

		returnMsg.put("return_code", code.getCode());
		returnMsg.put("result_order", result_order);
		returnMsg.put("result_data", result_data);
		returnMsg.put("return_msg", code.getMsg());

		ResponseUtil.wirte(response, new Gson().toJson(returnMsg));
	}

	public static void handResult(Map<String, Object> head,
			Map<String, Object> body, HttpServletResponse response)
			throws Exception {

		Map<String, Object> returnMsg = new HashMap<>();
		returnMsg.put("head", head);
		returnMsg.put("body", body);

		ResponseUtil.wirte(response, new Gson().toJson(returnMsg));
	}

}
